import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

const api = {
  openWindow: (name: WindowNameType, params?: any) => {
    ipcRenderer.send('openWindow', name, params)
  },
  closeWindow: (name: WindowNameType, type: WindowCloseType) => {
    ipcRenderer.send('closeWindow', name, type)
  },
  miniWindow: (name: WindowNameType) => {
    ipcRenderer.send('miniWindow', name)
  },
  screenWindow: (name: WindowNameType, isMax: boolean) => {
    ipcRenderer.send('screenWindow', name, isMax)
  },
  downloadFile: (fileUrl: string, fileName: string) => {
    ipcRenderer.send('downloadFile', fileUrl, fileName)
  },
  closeAllWindow: () => {
    ipcRenderer.send('closeAllWindow')
  },
  openChorm: (chromUrl: string) => {
    ipcRenderer.send('openChorm', chromUrl)
  },
  checkUpdate: () => {
    ipcRenderer.send('checkUpdate')
  },
  version: (callback) => {
    ipcRenderer.on('version', (_event: IpcRendererEvent, version) => callback(version))
  },
  downloadProgress: (callback) => {
    ipcRenderer.on('downloadProgress', (_event, progress) => {
      callback(progress)
    })
  },
  refreshInitData: () => {
    ipcRenderer.send('refreshInitData')
  },
  refreshData: (callback) => {
    ipcRenderer.on('refreshData', callback)
  },
  refreshCostData: (house_type: number) => {
    ipcRenderer.send('refreshCostData', house_type)
  },
  refCostData: (callback) => {
    ipcRenderer.on('refCostData', callback)
  },
  findSendMsg: (
    name: WindowNameType,
    handleType: string,
    currentPage: string,
    content: string,
    replaceContent?: string,
    editIds?: string,
  ) => {
    ipcRenderer.send('findSendMsg', name, handleType, currentPage, content, replaceContent, editIds)
  },
  acceptSendMsg: (callback) => {
    ipcRenderer.on(
      'acceptSendMsg',
      (_event: IpcRendererEvent, handleType, currentPage, content, replaceContent?, editIds?) =>
        callback(handleType, currentPage, content, replaceContent, editIds),
    )
  },
  pushDataLit: (callback) => {
    ipcRenderer.on('pushDataLit', (_event: IpcRendererEvent, dataList) => callback(dataList))
  },
  setWindowHeight: (name: WindowNameType, windowHeight: number) => {
    ipcRenderer.send('setWindowHeight', name, windowHeight)
  },
  sendListArray: (dataList: string) => {
    ipcRenderer.send('sendListArray', dataList)
  },
}
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
